package com.bsi.core.utils;


import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/*
 * Author: liusongs
 * Date: 2020/1/10 16:39
 * Content: java8lambda表达式的工具类，慢慢扩展
 */
public class StreamUtils {

    /**
     * 根据提供的方法来去重（只能搭配filter使用）
     *
     * @param function list里面存储对象所对应的方法
     * @param list     需要过滤的集合
     * @param <T>      所对应的泛型实体类
     * @return
     */
    public static <T> List<T> distinctList(Function<? super T, Object> function, List<T> list) {
        return list.stream().filter(distinctByKey(function)).collect(Collectors.toList());
    }

    protected static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> concurrentHashMap = new ConcurrentHashMap<>();
        return t -> concurrentHashMap.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }
}
